import Vue from 'vue'
import {
	login,
	getUserInfo
} from '@/api/index'



const user = {
	state: {
		// token: uni.getStorageSync('USER_TOKEN') || '',
		userInfo: uni.getStorageSync('USER_INFO'),
		// userInfo: uni.getStorageSync('USER_INFO') || {
		// 	avatar_url: "https://cdn.uviewui.com/uview/swiper/2.jpg",
		// 	birthday: "2023-08-01",
		// 	create_time: "2023-08-02 14:31:22",
		// 	id: 1,
		// 	mobile: "15228149112",
		// 	nickname: "阿杉",
		// 	open_id: "o20nh5JBax6t1OXbmgpyMXXv1mgI",
		// 	sex: true,
		// 	signature: "这是一个懒人",
		// 	order_num: 16,
		// 	coupon_num: 19,
		// 	favorite_num: 12,
		// 	history_num: 10
		// },
		timer: null,
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
			uni.setStorageSync('USER_TOKEN', token)
		},
		SET_USER_INFO: (state, info) => {
			state.userInfo = info
			uni.setStorageSync('USER_INFO', info)
		},
		SET_REFRESH_TIMER: (state, timer) => {
			state.timer = timer
		}
	},
	actions: {
		//登录
		login({
			dispatch,
			commit,
			state
		}, data) {
			// commit('SET_TOKEN', '123')
			// return
			return new Promise((resolve, reject) => {
				// login(data).then(res => {
				// commit('SET_TOKEN', res.data.token)
				commit('SET_TOKEN', 'test-token')
				// dispatch('getUserInfo')
				resolve({
					token: '123'
				})
				// }).catch((err) => {
				// 	reject(err)
				// })
			})
		},
		//获取用户信息
		getUserInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getUserInfo().then(res => {
					commit('SET_USER_INFO', res.data)
					resolve(res)
				}).catch((err) => {
					reject(err)
				})
			})
		},
		//退出登录
		logout({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				let data = {
					token: state.token
				}
				commit('SET_TOKEN', '')
				commit('SET_USER_INFO', {})
				uni.removeStorage({
					key: 'USER_INFO'
				});
				uni.removeStorage({
					key: 'USER_TOKEN'
				});
				uni.reLaunch({
					url: '/pages/login/login'
				})
				resolve()
				// logout(data).then(res => {
				// 	if (res.data.code === 200) {
				// 		commit('SET_TOKEN', '')
				// 		commit('SET_USER_INFO', {})
				// 		uni.clearStorageSync()
				// 	}
				// 	resolve(res)
				// }).catch((err) => {
				// 	reject(err)
				// })
			})
		}
	}
}

export default user